package com.gitee.srurl.core.util.login;

import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.gitee.srurl.core.cache.user.ApiUserCache;
import com.gitee.srurl.core.cache.user.dto.ApiUserExtend;
import com.gitee.srurl.core.constant.GlobalConstant;
import com.gitee.srurl.core.util.ServletUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.util.Optional;

/**
 * @author zxw
 * @date 2023/4/9 17:18
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public abstract class LoginHelper {

    private static final ThreadLocal<OperationUser> LOGIN_THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static OperationUser getLoginUser() {

        return LOGIN_THREAD_LOCAL.get();
    }

    public static OperationUser getLoginUserWithDefault() {

        return Optional.ofNullable(LOGIN_THREAD_LOCAL.get()).orElse(new OperationUser());
    }

    public static void setLoginUser(OperationUser loginUser) {

        LOGIN_THREAD_LOCAL.set(loginUser);
    }

    public static void removeLoginUser() {

        LOGIN_THREAD_LOCAL.remove();
    }

    public static String getToken() {

        return getToken(true);
    }

    public static String getToken(boolean removePrefix) {

        String token = ServletUtil.getRequest().getHeader(GlobalConstant.AUTHORIZATION);
        if (StrUtil.isBlank(token)) {
            return null;
        }

        if (removePrefix) {
            if (StrUtil.startWith(token, GlobalConstant.TOKEN_BEARER)) {
                token = StrUtil.sub(token, GlobalConstant.TOKEN_BEARER.length(), token.length());
            }
        }

        return token;
    }

    public static ApiUserExtend getApiUserExtend() {

        OperationUser loginUser = getLoginUser();
        if (loginUser == null) {
            return null;
        }
        Long userId = loginUser.getUserId();
        if (userId == null) {
            return null;
        }
        // 非api用户不返回信息
        if (!loginUser.getApi()) {
            return null;
        }
        return ApiUserCache.getApiUser(userId);
    }
}
